﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Markup;
using System.Xml.Linq;

namespace TestCommunityMvvmToolkit
{
    public static class ViewAware
    {
        static object? DefaultAware(object? data)
        {
            if (data is null) return null;

            var dtype = data.GetType();
            string? dname = dtype.Name;
            if (dname?.EndsWith("ViewModel") ?? false)
            {
                var vtype = Type.GetType(dtype.Namespace + "." + dtype.Name[..^5]);

                if (vtype != null)
                {
                    return (Control)Activator.CreateInstance(vtype)!;
                }
            }
            return new TextBlock { Text = "Not Found: " + dname };
        }

        public static object? Aware(object? data) => DefaultAware(data);

        public static DataTemplate? AttachDataTemplate(object? data)
        {
            if (data is null) return null;

            var view = Aware(data);
            if (view is null) return null;

            Type vtype = view.GetType();
            string className = vtype.Name;
            string? assemblyName = vtype.Assembly.FullName;
            string? namespaceName = vtype.Namespace;

            var context = new ParserContext();
            context.XmlnsDictionary.Add("", "http://schemas.microsoft.com/winfx/2006/xaml/presentation");
            context.XmlnsDictionary.Add("x", "http://schemas.microsoft.com/winfx/2006/xaml");
            context.XmlnsDictionary.Add("v", $"clr-namespace:{namespaceName};assembly={assemblyName}");

            string template_string = $"""
                <DataTemplate xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation">
                  <v:{className} />
                </DataTemplate >
                """;

            var dataTemplate = (DataTemplate)XamlReader.Parse(template_string, context);
            return dataTemplate;
        }
    }
}